package com.hgw.easyexcel3_demo.handler;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 图片格式修改拦截器
 *
 * @author Linhuibq-YanAn
 * @date 2022/10/20 16:11
 */
public class ImageCellWriteHandler implements CellWriteHandler {

    private List<String> repeats = new ArrayList<>();

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 在 数据转换成功后，不是头就把类型设置成空
        if (isHead) {
            return;
        }
        // 将要插入图片的单元格的type设置为空，下面由我们自定义填充图片
        if (!CollectionUtils.isEmpty(cellData.getImageDataList())) {
            cellData.setType(CellDataTypeEnum.EMPTY);
        }
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 在 单元格写入完后， 自己填充图片
        if (isHead || CollectionUtils.isEmpty(cellDataList)) {
            return;
        }
        Boolean listFlag = false;
        List<ImageData> data = null;
        Sheet sheet = cell.getSheet();
        // 判读是否具有图片
        if (!CollectionUtils.isEmpty(cellDataList.get(0).getImageDataList()) && cellDataList.size() > 0) {
            data = cellDataList.get(0).getImageDataList();
            if (data.size() > 1) {
                listFlag = true;
            }
        } else {
            return;
        }
        String key = cell.getRowIndex() + "_" + cell.getColumnIndex();
        if (repeats.contains(key)){
            return;
        }
        repeats.add(key);
        // 默认要导出的图片大小为60*60px,60px的行高大约是900,60px列宽大概是248*8
        sheet.getRow(cell.getRowIndex()).setHeight((short)900);
        sheet.setColumnWidth(cell.getColumnIndex(),listFlag?240*8*data.size():240*8);
        if (listFlag) {
            int i = 0;
            for (ImageData imageData : cellDataList.get(0).getImageDataList()) {
                this.insertImage(sheet,cell,imageData.getImage(),i);
            }
        } else {
            // 如果是单张图片只需要写入一个单元格
            this.insertImage(sheet,cell,cellDataList.get(0).getImageDataList().get(0).getImage(),0);
        }
    }

    private void insertImage(Sheet sheet,Cell cell,byte[] pictureData,int i){
        int picWidth = Units.pixelToEMU(60);
        int index = sheet.getWorkbook().addPicture(pictureData, HSSFWorkbook.PICTURE_TYPE_PNG);
        Drawing drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            drawing = sheet.createDrawingPatriarch();
        }
        CreationHelper helper = sheet.getWorkbook().getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();
        // 设置图片坐标
        anchor.setDx1(picWidth*i);
        anchor.setDx2(picWidth+picWidth*i);
        anchor.setDy1(0);
        anchor.setDy2(0);
        //设置图片位置
        anchor.setCol1(cell.getColumnIndex());
        anchor.setCol2(cell.getColumnIndex());
        anchor.setRow1(cell.getRowIndex());
        anchor.setRow2(cell.getRowIndex() + 1);
        // 设置图片可以随着单元格移动
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
        drawing.createPicture(anchor, index);
    }

}
